import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:psi/entity/sales_entity.dart';

import '../../../../theme/app_colors.dart';
import '../../../../utils/utils.dart';
import '../../../../utils/widget_util.dart';
import '../../../../widgets/app_bar.dart';
import '../../../../widgets/gesture.dart';
import '../../../../widgets/text_widget.dart';
import 'sales_add_logic.dart';

class SalesAddPage extends StatelessWidget {
  final logic = Get.find<SalesAddLogic>();
  final state = Get
      .find<SalesAddLogic>()
      .state;

  Widget orderWidget() {
    return WidgetUtil.getCardItem(
        radius: BorderRadius.all(Radius.circular(16)),
        padding: EdgeInsets.symmetric(vertical: 16),
        child: Column(
          children: [
            Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.only(topRight: Radius.circular(6), bottomRight: Radius.circular(6)),
                  child: Container(
                    height: 30,
                    width: 6,
                    color: primaryColor,
                  ),
                ),
                8.horizontalSpace,
                TextWidget(
                  "销售单",
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: primaryColor,
                )
              ],
            ),
            16.verticalSpace,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: Obx(() {
                return Column(
                  children: [
                    WidgetUtil.itemInputWidget(
                        title: "销售人",
                        canEdit: state.isEdit.value,
                        value: state.sales.value.sellUserName,
                        onChange: (value) {
                          state.sales.value.sellUserName = value;
                        }),
                    8.verticalSpace,
                    WidgetUtil.itemInputWidget(
                        title: "联系方式",
                        canEdit: state.isEdit.value,
                        value: state.sales.value.sellPhone,
                        inputType: TextInputType.phone,
                        onChange: (value) {
                          state.sales.value.sellPhone = value;
                        }),
                    8.verticalSpace,
                    WidgetUtil.itemInputWidget(
                        title: "总金额（元）",
                        canEdit: state.isEdit.value,
                        value: Utils.getFormatStepCount(amount: state.sales.value.realAmount),
                        inputType: TextInputType.numberWithOptions(decimal: true),
                        onChange: (value) {
                          state.sales.value.realAmount = num.tryParse(value);
                          logic.update(["amount"]);
                        }),
                    8.verticalSpace,
                    WidgetUtil.itemInputWidget(
                        title: "已支付（元）",
                        canEdit: state.isEdit.value,
                        value: Utils.getFormatStepCount(amount: state.sales.value.payAmount),
                        inputType: TextInputType.numberWithOptions(decimal: true),
                        onChange: (value) {
                          state.sales.value.payAmount = num.tryParse(value);
                        }),
                    8.verticalSpace,
                    WidgetUtil.pickTimeWidget(
                        title: "销售时间",
                        canEdit: state.isEdit.value,
                        value: DateTime.now(),
                        onDone: (time) {
                          state.sales.value.recordTime = DateUtil.formatDate(time, format: DateFormats.full);
                        }),
                  ],
                );
              }),
            ),
          ],
        ));
  }

  Widget orderItemWidget() {
    return WidgetUtil.getCardItem(
        radius: BorderRadius.all(Radius.circular(16)),
        padding: EdgeInsets.symmetric(vertical: 16),
        child: Column(
          children: [
            Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.only(topRight: Radius.circular(6), bottomRight: Radius.circular(6)),
                  child: Container(
                    height: 30,
                    width: 6,
                    color: primaryColor,
                  ),
                ),
                8.horizontalSpace,
                TextWidget(
                  "销售产品",
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: primaryColor,
                ),
                Spacer(),
                Obx(() {
                  return Offstage(
                    offstage: !state.isEdit.value,
                    child: Container(
                      width: 24,
                      height: 24,
                      child: IconButton(onPressed: logic.addAction, padding: EdgeInsets.zero, icon: Icon(Icons.add_circle_outline, size: 24, color: primaryColor)),
                    ),
                  );
                }),
                16.horizontalSpace,
              ],
            ),
            16.verticalSpace,
            GetBuilder<SalesAddLogic>(
                id: "item",
                builder: (logic) {
                  return WidgetUtil.listViewWithSeparated(
                    children: List.generate(state.sales.value.itemList!.length, (index) {
                      SalesItem item = state.sales.value.itemList![index];
                      return itemWidget(item);
                    }),
                  );
                }),
            16.verticalSpace,
          ],
        ));
  }

  Widget itemWidget(SalesItem item) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Expanded(
            child: WidgetUtil.getCardItem(
                radius: BorderRadius.all(Radius.circular(16)),
                color: Color(0xFFF9F9F9),
                child: Column(
                  children: [
                    GetBuilder<SalesAddLogic>(
                        id: "itemName",
                        builder: (logic) {
                          return WidgetUtil.itemInputWidget(
                              title: "名称",
                              value: item.name,
                              onChange: (value) {
                                item.name = value;
                              });
                        }),
                    8.verticalSpace,
                    Row(
                      children: [
                        SizedBox(
                          width: 100,
                        ),
                        Expanded(
                          child: GetBuilder<SalesAddLogic>(
                              id: "itemRecentNames",
                              builder: (logic) {
                                return Wrap(
                                    runSpacing: 8,
                                    spacing: 8,
                                    children: List.generate(
                                        state.recentNames.value.isEmpty
                                            ? 0
                                            : state.recentNames.value.length >= state.count.value
                                            ? state.recentNames.value.length + 1
                                            : state.recentNames.value.length, (index) {
                                      String name = state.recentNames.value.length >= state.count.value
                                          ? (index == state.recentNames.value.length ? "更多" : state.recentNames.value[index % state.recentNames.value.length])
                                          : state.recentNames.value[index % state.recentNames.value.length];
                                      return WidgetUtil.getCardItem(
                                          onTap: () async {
                                            if (!state.isEdit.value) {
                                              return;
                                            }
                                            if (name == "更多") {
                                              await logic.getRecentNames(count: state.count.value + 3);
                                            } else {
                                              item.name = name;
                                              logic.update(["itemName", "itemRecentNames"]);
                                            }
                                          },
                                          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                          color: item.name == name ? primaryColor : Colors.white,
                                          child: TextWidget(
                                            name,
                                            fontSize: 14,
                                            color: item.name == name ? Colors.white : primaryColor,
                                          ));
                                    }).toList());
                              }),
                        ),
                      ],
                    ),
                    8.verticalSpace,
                    Obx(() {
                      return WidgetUtil.itemInputWidget(
                          title: "规格",
                          canEdit: state.isEdit.value,
                          value: item.standards,
                          onChange: (value) {
                            item.standards = value;
                          });
                    }),
                    8.verticalSpace,
                    Obx(() {
                      return WidgetUtil.itemInputWidget(
                          title: "尺寸",
                          canEdit: state.isEdit.value,
                          value: item.size,
                          onChange: (value) {
                            item.size = value;
                          });
                    }),
                    8.verticalSpace,
                    Obx(() {
                      return WidgetUtil.itemInputWidget(
                          title: "材质",
                          canEdit: state.isEdit.value,
                          value: item.material,
                          onChange: (value) {
                            item.material = value;
                          });
                    }),
                    8.verticalSpace,
                    Obx(() {
                      return WidgetUtil.itemInputWidget(
                          title: "数量",
                          canEdit: state.isEdit.value,
                          value: item.count?.toString(),
                          inputType: TextInputType.number,
                          onChange: (value) {
                            item.count = num.tryParse(value);
                            logic.update(["amount"]);
                          });
                    }),
                    8.verticalSpace,
                    Obx(() {
                      return WidgetUtil.itemInputWidget(
                          title: "价格",
                          canEdit: state.isEdit.value,
                          value: item.price?.toString(),
                          inputType: TextInputType.numberWithOptions(decimal: true),
                          onChange: (value) {
                            item.price = num.tryParse(value);
                            logic.update(["amount"]);
                          });
                    }),
                    8.verticalSpace,
                    Obx(() {
                      return WidgetUtil.itemInputWidget(
                          value: item.mark,
                          title: "备注",
                          canEdit: state.isEdit.value,
                          onChange: (value) {
                            item.mark = value;
                          });
                    }),
                  ],
                )),
          ),
          8.horizontalSpace,
          Container(
            width: 24,
            height: 24,
            child: Obx(() {
              return Offstage(
                offstage: !state.isEdit.value || (state.isEdit.value && state.sales.value.itemList!.length == 1),
                child: IconButton(
                  onPressed: () => logic.deleteAction(item),
                  padding: EdgeInsets.zero,
                  icon: Icon(Icons.cancel_rounded, size: 24, color: Colors.red),
                ),
              );
            }),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        title: "添加销售",
        actions: [
          Obx(() {
            return ClickWidget(
              onTap: logic.clickAction,
              child: TextWidget(
                state.isEdit.value ? "完成" : "编辑",
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            );
          }),
          16.horizontalSpace
        ],
      ),
      body: GetBuilder<SalesAddLogic>(
          id: "all",
          builder: (logic) {
            return Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 16),
                      child: Column(
                        children: [
                          16.verticalSpace,
                          orderWidget(),
                          16.verticalSpace,
                          orderItemWidget(),
                          16.verticalSpace,
                        ],
                      ),
                    ),
                  ),
                ),
                WidgetUtil.getCardItem(
                    padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight, top: 8),
                    radius: BorderRadius.vertical(top: Radius.circular(32)),
                    color: primaryColor,
                    child: Container(
                      height: 64,
                      padding: EdgeInsets.symmetric(horizontal: 16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          TextWidget(
                            "总计:",
                            fontSize: 16,
                            color: Colors.white,
                          ),
                          GetBuilder<SalesAddLogic>(
                              id: "amount",
                              builder: (logic) {
                                return Column(
                                  children: [
                                    TextWidget(
                                      "${state.sales.value.totalCount} 件商品",
                                      fontSize: 16,
                                      color: Colors.white,
                                    ),
                                    TextWidget(
                                      "￥ ${state.sales.value.totalAmount} 元",
                                      fontSize: 16,
                                      color: Colors.white,
                                    ),
                                  ],
                                );
                              }),
                        ],
                      ),
                    ))
              ],
            );
          }),
    );
  }
}
